package com.tourism.home.controller.common;

import com.tourism.home.entity.Result;
import com.tourism.home.enums.ResultEnum;
import com.tourism.home.exceptions.GlobalException;
import com.tourism.home.service.EmailService;
import com.tourism.home.utils.ResultUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class EmailController {

    @Autowired
    HttpServletRequest httpServletRequest;


    @Autowired
    EmailService emailService;

    /**
     * 注册邮箱时发送邮箱验证码
     * @param email
     * @return
     */
    @GetMapping("/send/code/{email}")
    Result send(@PathVariable(value = "email") String email){
        emailService.send(email);
        return ResultUtil.success("邮箱验证码已发送!");
    }

    /**
     * 注册邮箱时发送邮箱验证码
     * @param email
     * @return
     */
    @GetMapping("/send/code_p/{email}")
    Result forgetPassword(@PathVariable(value = "email") String email){
        emailService.forgetPassword(email);
        return ResultUtil.success("邮箱验证码已发送!");
    }

    /**
     * 验证用户输入的验证码和邮箱是否匹配
     * @param email
     * @param yzcode
     * @return
     * @throws GlobalException
     */
    @PostMapping("/check/code")
    Result checkCode(@Param("email") String email, @Param(value = "yzcode") String yzcode) throws GlobalException {
        HttpSession httpSession = httpServletRequest.getSession();
        if(httpSession.getAttribute("yzcode") == null || httpSession.getAttribute("email") == null){
            throw new GlobalException(ResultEnum.NO_CODE_ERROR);
        }else if (httpSession.getAttribute("email").equals(email) && httpSession.getAttribute("yzcode").equals(yzcode)) {
            System.out.println(yzcode);
            return ResultUtil.success(true);
        }else {
            return ResultUtil.error("请检查邮箱验证码!");
        }
    }

}
